# -*- coding: utf-8 -*-

# 设计一个streamlit的聊天界面，调用ai.gitee.com/v1的api端口进行对话补全。要求界面友好，配色美观。直接提供完整代码，不要解释代码。
#  调试错误： stream=True的解码识别不好，无法实时显示。改为stream=false成功。

import streamlit as st
import requests
import os
import time

# API配置
API_KEY = "YOU KEY"
API_URL = "https://ai.gitee.com/v1/chat/completions"
model_name = "Qwen2.5-7B-Instruct"
# ollama
# API_KEY = "."
# API_URL = "http://localhost:11434/v1/chat/completions"
# model_name = "qwen2.5:3b"



# 界面配置
st.set_page_config(
    page_title="Gitee AI Chat",
    page_icon="🤖",
    layout="centered",
    initial_sidebar_state="collapsed"
)

# 自定义CSS样式
st.markdown("""
<style>
[data-testid="stAppViewContainer"] {
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

[data-testid="stHeader"] {
    background: rgba(0,0,0,0);
}

[data-testid="stChatMessage"] {
    padding: 1.5rem;
    border-radius: 1rem;
    margin: 1rem 0;
}

.user-message {
    background: #ffffff;
    border: 1px solid #e0e0e0;
}

.assistant-message {
    background: #007bff;
    color: white;
}

[data-testid="stVerticalBlock"] > div:has(> [data-testid="stChatMessage"]) {
    gap: 0.8rem;
}
</style>
""", unsafe_allow_html=True)

# 初始化对话历史
if "messages" not in st.session_state:
    st.session_state.messages = []

# 主界面
st.title("🎈 Gitee AI 聊天助手")
st.caption("体验智能对话，输入消息开始交流")

# 显示历史消息
for msg in st.session_state.messages:
    with st.chat_message(msg["role"], avatar=("👤" if msg["role"] == "user" else "🤖")):
        st.markdown(msg["content"])

# 处理用户输入
if prompt := st.chat_input("输入您的消息..."):
    # 添加用户消息
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user", avatar="👤"):
        st.markdown(prompt)

    # 生成AI回复
    with st.chat_message("assistant", avatar="🤖"):
        message_placeholder = st.empty()
        full_response = ""
        
        try:
            headers = {
                "Authorization": f"Bearer {API_KEY}",
                "Content-Type": "application/json"
            }
            
            payload = {
                "model": model_name,
                "messages": st.session_state.messages,
                "temperature": 0.7,
                # "stream": True
            }
            
            response = requests.post(
                API_URL,
                headers=headers,
                json=payload,
            )

            # st.error(f"response: {str(response.json())}")
            if response.status_code == 200:
                full_response = response.json()["choices"][0]["message"]["content"]
            else:
                full_response = f"Error: {response.status_code} - {response.text}"

            
            message_placeholder.markdown(full_response)
            st.session_state.messages.append({"role": "assistant", "content": full_response})
            
        except Exception as e:
            st.error(f"请求出错: {str(e)}")
            st.session_state.messages.pop()